<?php

namespace App\Console\Commands;

use DB;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class GeoaddShop extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shopinfo:geoaddShop';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '缓存商铺位置信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 检测脚本是否重复执行
        $this->check();
        //清楚redis数据
        Redis::del('location');
        DB::table('s_shanghu')->select('id', 'lng', 'lat')->orderBy("id", 'asc')->chunk(5, function ($infos) {
            foreach ($infos as $info) {
                Redis::geoadd('location', $info->lng, $info->lat, $info->id);
            }
        });
        exit('ok');
    }

    public function check()
    {
        $file = 'shopinfo_geoaddShop.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
